package com.zhongfl.crm.lixiao.batch.service;

import com.heptagram.core.common.util.JSONUtil;
import com.heptagram.lixiao.api.LiXiaoService;
import com.heptagram.lixiao.bean.LXResponse;
import com.heptagram.lixiao.bean.LiXiaoConsts;
import com.heptagram.lixiao.bean.enums.ContractStatus;
import com.heptagram.lixiao.bean.enums.OpportunityStage;
import com.heptagram.lixiao.bean.request.LXAssistAddUserReq;
import com.heptagram.lixiao.bean.request.contract.LXContractInfo;
import com.heptagram.lixiao.bean.request.contract.LXContractUpdateRequest;
import com.heptagram.lixiao.bean.request.opportunity.LXOpportunity;
import com.heptagram.lixiao.bean.request.opportunity.LXOpportunityAssistUserRequest;
import com.heptagram.lixiao.bean.request.opportunity.LXOpportunityRequest;
import com.heptagram.lixiao.bean.response.LXUserResponse;
import com.heptagram.lixiao.bean.response.opportunity.LXOpportunityAssistUserResponse;
import com.heptagram.lixiao.bean.response.opportunity.LXOpportunityResponse;
import com.heptagram.lixiao.common.exception.LiXiaoErrorException;
import com.zhongfl.crm.lixiao.bean.LiXiaoException;
import com.zhongfl.crm.lixiao.common.LxStatusConvertUtils;
import com.zhongfl.crm.lixiao.mapper.LXOrderMapper;
import com.zhongfl.crm.lixiao.mapper.OrderAssistUserMapper;
import com.zhongfl.crm.model.LxDepartment;
import com.zhongfl.crm.model.LxUser;
import com.zhongfl.crm.model.boss.*;
import com.zhongfl.crm.service.LxDepartmentService;
import com.zhongfl.crm.service.LxUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import tech.heptagram.channel.api.model.Channel;
import tech.heptagram.channel.api.service.ChannelService;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * boss订单信息同步到励销 服务
 * 1. boss订单状态
 * 2. boss添加协作人
 *
 * @author wang.yuchuan
 * @date 2018/6/28
 */
@Service
@Slf4j
public class OrderSyncFromBoss2LXService {

    @Resource
    private LiXiaoService liXiaoService;

    @Resource
    private LXOrderMapper lxOrderMapper;

    @Resource
    private LxUserService lxUserService;

    @Resource
    private OrderAssistUserMapper orderAssistUserMapper;

    @Resource
    private LxDepartmentService lxDepartmentService;

    @Resource
    private ChannelService channelService;


    /**
     * 从boss同步到励销
     */
    public void sync(OrderTaskLog orderTaskLog) {
        if (Objects.isNull(orderTaskLog)) {
            return;
        }
        try {
            switch (orderTaskLog.getType()) {
                // 1. 客户订单基本信息同步
                case CUSTOMER_INFORMATION_CHANGE:
                    syncCustomerOrder(orderTaskLog);
                    break;
                // 2. 交付订单状态变更同步
                case ORDER_STATUS_CHANGE:
                    syncOrderStatus(orderTaskLog);
                    break;
                // 3. 交付订单协作人同步
                case ORDER_ASSIST_USER_CHANGE:
                    syncCommon(orderTaskLog);
                    break;
                // 4. 交付订单基本信息同步
                case ORDER_ESSENTIAL_INFORMATION_CHANGE:
                    syncEssentialInformation(orderTaskLog);
                    break;
                // 5.同步删除励销的客户订单
                case CUSTOMER_ORDER_CANCEL:
                    syncCancelCustomerOrder(orderTaskLog);
                    break;
                default:
                    break;
            }
        } catch (Exception ex) {
            log.error("同步订单信息错误: {}", ex.getMessage(), ex);
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }



    /**
     * 一、客户订单基本信息同步
     */
    private void syncCustomerOrder(OrderTaskLog orderTaskLog) throws IOException, InterruptedException, LiXiaoErrorException {
        log.info("开始同步客户订单信息到励销, content:{}", orderTaskLog.getContent());

        CustomerOrder customerOrder = JSONUtil.fromJson(orderTaskLog.getContent(), CustomerOrder.class);
        if (Objects.isNull(customerOrder) || Objects.isNull(customerOrder.getCustomerOrderStatus())) {
            throw new LiXiaoException("同步客户订单信息失败: 订单或状态为空: " + orderTaskLog.getContent());
        }

        LxOrder lxOrder = lxOrderMapper.selectByOrderNo(customerOrder.getCustomerOrderNo());
        if (Objects.isNull(lxOrder)) {
            throw new LiXiaoException("同步订单状态失败: 订单非励销订单 " + orderTaskLog.getOrderNo());
        }

        OpportunityStage opportunityStage = LxStatusConvertUtils.convertCustomerOrderStatus2LxOpportunityStage(customerOrder.getCustomerOrderStatus());
        if (Objects.nonNull(opportunityStage)) {
            LXOpportunityRequest request = buildOpportunity(opportunityStage, customerOrder);

            Thread.sleep(2000);
            liXiaoService.getOpportunityService().updateOpportunity(request);
        }

        //updateLxOrder(lxOrder,customerOrder);
    }

    /**
     * 根据客户订单构造更新对象，没判空的是必填字段
     */
    private LXOpportunityRequest buildOpportunity(OpportunityStage opportunityStage, CustomerOrder customerOrder) {
        LXOpportunity lxOpportunity = new LXOpportunity();
        lxOpportunity.setId(customerOrder.getLxCustomerOrderId());
        lxOpportunity.setTitle(customerOrder.getCustomerName());

        Channel channel = channelService.findById(customerOrder.getChannelId());
        lxOpportunity.setCustomerId(channel.getLxCustomerId());
        lxOpportunity.setStage(String.valueOf(opportunityStage.getId()));
        if (Objects.nonNull(customerOrder.getLoanAmount())) {
            lxOpportunity.setExpectAmount(customerOrder.getLoanAmount().toEngineeringString());
        }
        if (Objects.nonNull(customerOrder.getLoanDuration())) {
            lxOpportunity.setNumericAssetF59409(customerOrder.getLoanDuration());
        }

        LXOpportunityRequest request = new LXOpportunityRequest();
        request.setId(lxOpportunity.getId());
        request.setOpportunity(lxOpportunity);

        return request;
    }

    /**
     * 二、交付订单状态变更同步
     */
    private void syncOrderStatus(OrderTaskLog orderTaskLog) throws IOException, LiXiaoErrorException, InterruptedException {

        log.info("开始同步订单状态到励销, content:{}", orderTaskLog.getContent());

        Order order = JSONUtil.fromJson(orderTaskLog.getContent(), Order.class);
        if (Objects.isNull(order) || Objects.isNull(order.getStatus())) {
            throw new LiXiaoException("同步订单状态失败: 订单或状态为空: " + orderTaskLog.getContent());
        }

        LxOrder lxOrder = lxOrderMapper.selectByOrderNo(order.getOrderNo());
        if (Objects.isNull(lxOrder)) {
            throw new LiXiaoException("同步订单状态失败: 订单非励销订单 " + orderTaskLog.getOrderNo());
        }

        ContractStatus contractStatus = LxStatusConvertUtils.convertDeliverOrderStatus2LxContractStage(order.getStatus());
        if (Objects.nonNull(contractStatus)) {
            LXContractUpdateRequest lxContractUpdateRequest = buildContractUpdateRequest(order, contractStatus);

            Thread.sleep(2000);
            liXiaoService.getContractService().updateContract(lxContractUpdateRequest);
        }
    }

    /**
     * 根据交付订单构造更新对象，没判空的是必填字段
     */
    private LXContractUpdateRequest buildContractUpdateRequest(Order order, ContractStatus contractStatus) {
        LXContractInfo saveContract = new LXContractInfo();

        saveContract.setId(order.getLxDeliverOrderId());

        saveContract.setTitle(order.getName());

        Channel channel = channelService.findById(order.getChannelId());
        saveContract.setCustomerId(channel.getLxCustomerId());

        saveContract.setApproveStatus(LiXiaoConsts.ContractApprovalStatus.APPROVED);

        saveContract.setSn(order.getOrderNo());
        saveContract.setStatus(String.valueOf(contractStatus.getId()));
        saveContract.setTotalAmount(order.getLoanAmount());

        LxUser lxUser = lxUserService.findByStaffCode(order.getBusinessManagerStaffCode());
        saveContract.setUserId(lxUser.getLxId());

        LXContractUpdateRequest request = new LXContractUpdateRequest();
        request.setId(saveContract.getId());
        request.setContract(saveContract);

        return request;
    }

    /**
     * 三、同步协作人
     */
    private void syncCommon(OrderTaskLog orderTaskLog) throws LiXiaoErrorException, InterruptedException {
        String orderNo = orderTaskLog.getOrderNo();
        log.info("同步订单协作人信息到励销, orderNo:{}", orderNo);
        //通过订单号查询
        List<OrderAssistUser> orderAssistUserList = orderAssistUserMapper.selectByOrderNo(orderNo);
        if (CollectionUtils.isEmpty(orderAssistUserList)) {
            throw new LiXiaoException("同步订单协作人失败: 订单协作人为空: " + orderTaskLog.getContent());
        }
        //查询励销订单
        LxOrder lxOrder = lxOrderMapper.selectByOrderNo(orderTaskLog.getOrderNo());
        if (Objects.isNull(lxOrder)) {
            throw new LiXiaoException("订单不存在");
        }

        List<Long> opportunityAssists = new ArrayList<>();
        //if (Objects.nonNull(lxOrder.getLxId())) {
        //    // 查询励销交付订单的协作人
        //    LXOpportunityAssistUserRequest request1 = new LXOpportunityAssistUserRequest();
        //    request1.setId(lxOrder.getLxId());
        //    //获取到励销的协作人
        //    LXOpportunityAssistUserResponse assistUsers = liXiaoService.getOpportunityService().findAssistUsers(request1);
        //    List<LXUserResponse.User> assistUsersList = assistUsers.getData().getAssistUsers();
        //    for (LXUserResponse.User user : assistUsersList) {
        //        opportunityAssists.add(user.getId());
        //    }
        //    //同步交付订单
        //    syncOpportunity(lxOrder.getLxId(), orderAssistUserList, opportunityAssists);
        //}

        // 查询励销批贷订单的协作人
        List<Long> contractAssistsIds = new ArrayList<>();
        //if (Objects.nonNull(lxOrder.getLxContractId())) {
        if (Objects.nonNull(lxOrder.getLxId())) {
            LXOpportunityAssistUserRequest request2 = new LXOpportunityAssistUserRequest();
            request2.setId(lxOrder.getLxContractId());

            Thread.sleep(2000);
            LXOpportunityAssistUserResponse contractAssists = liXiaoService.getContractService().findAssistUsers(request2);
            List<LXUserResponse.User> assistUsersList2 = contractAssists.getData().getAssistUsers();
            for (LXUserResponse.User user : assistUsersList2) {
                contractAssistsIds.add(user.getId());
            }
            //同步批贷订单
            synContract(lxOrder.getLxContractId(), orderAssistUserList, contractAssistsIds);
        }

        //同时同步到BOSS系统
        syncOrderAssistUserToBoss(opportunityAssists, contractAssistsIds, lxOrder);
    }

    private void syncOrderAssistUserToBoss(List<Long> opportunityAssists, List<Long> contractAssistsIds, LxOrder lxOrder) {
        opportunityAssists.addAll(contractAssistsIds);
        List<Long> userIds = opportunityAssists.stream().distinct().collect(Collectors.toList());
        if (!userIds.isEmpty()) {
            List<OrderAssistUser> orderAssistUserList = orderAssistUserMapper.selectByOrderNo(lxOrder.getOrderNo());
            List<String> collect = new ArrayList<>();
            if (!orderAssistUserList.isEmpty()) {
                collect = orderAssistUserList.stream().map(OrderAssistUser::getStaffCode).collect(Collectors.toList());
            }
            for (Long userId : userIds) {
                LxUser lxUser = lxUserService.findByLxId(userId);
                if (collect.contains(lxUser.getStaffCode())) {
                    continue;
                }
                //协作人的信息
                OrderAssistUser orderAssistUser = new OrderAssistUser();
                orderAssistUser.setCreatedBy("SYSTEM");
                orderAssistUser.setModifiedBy("SYSTEM");
                orderAssistUser.setOrderNo(lxOrder.getOrderNo());
                orderAssistUser.setStaffCode(lxUser.getStaffCode());
                orderAssistUser.setStaffName(lxUser.getStaffName());
                LxDepartment lxDepartment = lxDepartmentService.findByLxId(lxUser.getDepartmentId());
                orderAssistUser.setAmibaName(lxDepartment.getName());
                orderAssistUser.setAmibaId(lxDepartment.getAmibaId());
                log.info("开始同步订单协作人信息到BOSS, orderAssistUser:{}", orderAssistUser);
                orderAssistUserMapper.insert(orderAssistUser);
                log.info("结束同步订单协作人信息到BOSS, orderAssistUser:{}", orderAssistUser);
            }
        }
    }

    private void syncOpportunity(Long id, List<OrderAssistUser> orderAssistUserList, List<Long> assistUserIds) throws LiXiaoErrorException {
        LXAssistAddUserReq lxAssistAddUserReq = new LXAssistAddUserReq();
        lxAssistAddUserReq.setId(id);
        LXAssistAddUserReq.OpportunityAssistUser assistUser = new LXAssistAddUserReq.OpportunityAssistUser();
        for (OrderAssistUser orderAssistUser : orderAssistUserList) {
            LxUser lxUser = lxUserService.findByStaffCode(orderAssistUser.getStaffCode());
            log.info("交付订单协作人 {}", lxUser);
            if (assistUserIds.contains(lxUser.getLxId())) {
                continue;
            }
            assistUserIds.add(lxUser.getLxId());
        }
        assistUser.setAssistUserIds(assistUserIds);
        lxAssistAddUserReq.setOpportunity(assistUser);
        LXResponse lxResponse = liXiaoService.getOpportunityService().updateAssistUsers(lxAssistAddUserReq);
        log.info("添加协作人返回的结果: {}", lxResponse);
    }

    private void synContract(Long id, List<OrderAssistUser> orderAssistUserList, List<Long> assistUserIds) throws LiXiaoErrorException, InterruptedException {
        LXAssistAddUserReq lxAssistAddUserReq = new LXAssistAddUserReq();
        lxAssistAddUserReq.setId(id);
        LXAssistAddUserReq.ContractAssistUser assistUser = new LXAssistAddUserReq.ContractAssistUser();
        for (OrderAssistUser orderAssistUser : orderAssistUserList) {
            LxUser lxUser = lxUserService.findByStaffCode(orderAssistUser.getStaffCode());
            log.info("批贷订单协作人 {}", lxUser);
            assistUserIds.add(lxUser.getLxId());
        }
        assistUser.setAssistUserIds(assistUserIds);
        lxAssistAddUserReq.setContract(assistUser);

        Thread.sleep(2000);
        LXResponse lxResponse = liXiaoService.getContractService().updateAssistUsers(lxAssistAddUserReq);
        log.info("添加协作人返回的结果: {}", lxResponse);
    }

    /**
     * 四、交付订单同步基本信息
     */
    private void syncEssentialInformation(OrderTaskLog orderTaskLog) throws IOException, LiXiaoErrorException, InterruptedException {
        log.info("开始同步订单基本信息到励销, content:{}", orderTaskLog.getContent());

        Order order = JSONUtil.fromJson(orderTaskLog.getContent(), Order.class);
        if (Objects.isNull(order) || Objects.isNull(order.getOrderNo())) {
            throw new LiXiaoException("同步订单基本信息失败: 订单为空: " + orderTaskLog.getContent());
        }

        syncContractEssentialInformation(order);

        log.info("同步订单基本信息到励销完成！");
    }

    private void syncContractEssentialInformation(Order order) throws LiXiaoErrorException, InterruptedException {
        LxOrder lxOrder = lxOrderMapper.selectByOrderNo(order.getOrderNo());

        LXContractUpdateRequest request = new LXContractUpdateRequest();
        request.setId(lxOrder.getLxId());

        LXContractInfo lxContractInfo = new LXContractInfo();
        //for (ContractStatus contractStatus : ContractStatus.values()) {
        //    if (order.getStatus().name().equals(contractStatus.name())){
        //        lxContractInfo.setStatus(String.valueOf(contractStatus.getId()));
        //    }
        //}
        lxContractInfo.setCustomerId(lxOrder.getCustomerId());

        if (StringUtils.isNotEmpty(order.getName())) {
            lxContractInfo.setTitle(order.getName());
        }
        if (Objects.nonNull(order.getLoanAmount())) {
            lxContractInfo.setTotalAmount(order.getLoanAmount());
        }
        if (Objects.nonNull(order.getLoanDuration())) {
            lxContractInfo.setNumericAsset_Ffae20(order.getLoanDuration());
        }

        request.setContract(lxContractInfo);

        Thread.sleep(2000);
        liXiaoService.getContractService().updateContract(request);
    }

    /**
     * ️五,同步取消励销的客戶订单
     * @param orderTaskLog
     */
    private void syncCancelCustomerOrder(OrderTaskLog orderTaskLog) throws IOException, LiXiaoErrorException {
        //BOSS里取消客戶订单  励销里将客户订单修改为输单
        String orderNo = orderTaskLog.getOrderNo();
        log.info("同步取消客戶订单到励销, orderNo:{}", orderNo);
        CustomerOrder customerOrder = JSONUtil.fromJson(orderTaskLog.getContent(), CustomerOrder.class);
        Long lxCustomerOrderId = customerOrder.getLxCustomerOrderId();
        LXOpportunityResponse lxOpportunityResponse = liXiaoService.getOpportunityService().findOpportunityByOrderId(lxCustomerOrderId);
        if(Objects.nonNull(lxOpportunityResponse)){
            OpportunityStage opportunityStage = LxStatusConvertUtils.convertCustomerOrderStatus2LxOpportunityStage(customerOrder.getCustomerOrderStatus());
            if(lxOpportunityResponse.getData().getStage().equals(opportunityStage.getId())){
                return;
            }else{
                LXOpportunityRequest request = buildOpportunity(opportunityStage, customerOrder);
                liXiaoService.getOpportunityService().updateOpportunity(request);
            }
        }
    }
}
